package compiler;

import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;

import compiler.code_generator.*;
import compiler.parser.ProgramParser;
import compiler.scanner.Scanner;
import jasmin.Main;
import compiler.semantics.SemanticAnalyzer;
import compiler.syntax_tree.Program;

public class Compiler
{
    private static final String INTERMEDIATE_FILE_NAME = "intermediate.j";

    public Compiler(String filename)
    {
        try
        {
            InputStreamReader reader = new InputStreamReader(new FileInputStream(filename));
            ProgramParser parser = new ProgramParser(new Scanner(reader));

            Program program = parser.parse();
            if (!parser.WasError())
            {
                SemanticAnalyzer semanticAnalyzer = new SemanticAnalyzer(program.mainClass);
                semanticAnalyzer.analyze();
                CodeGenerator codeGenerator = new CodeGenerator(new MinijavaFilePattern());
                String codeFileContents = codeGenerator.generateCodeFileContents(program);
                runAssembler(codeFileContents);
            }
        }
        catch (Exception ex)
        {
            System.out.println("Compilation Error: " + ex.getMessage());
        }
    }

    public void runAssembler(String codeFileContents)
    {
        try
        {
            PrintWriter printWriter = new PrintWriter(INTERMEDIATE_FILE_NAME);
            printWriter.println(codeFileContents);
            printWriter.close();
            new Main().assemble(INTERMEDIATE_FILE_NAME);
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}
